package br.mikhas.container.factory.processor;

import br.mikhas.container.config.BeanDefinition;
import br.mikhas.container.config.InitializingBean;
import br.mikhas.container.factory.BeanFactory;
import br.mikhas.container.factory.BeanPostProcessor;
import br.mikhas.reflector.Reflect;

/**
 * Calls the initializing method after the bean creation and property set
 * 
 * @author Mikhail Domanoski
 * 
 */
public final class BeanInitializingPostProcessor implements BeanPostProcessor {

	/**
	 * It's process only bean which have the initializing method
	 */
	@Override
	public boolean mayProcess(BeanDefinition definition) {

		String init = definition.initializingMethod();

		boolean methodDef = init != null && !init.isEmpty();

		Class<?> type = definition.getType();

		return methodDef || InitializingBean.class.isAssignableFrom(type);

	}

	/**
	 * Calls the initializing method
	 */
	@Override
	public Object processBean(BeanDefinition definition, Object resource) {

		if (resource instanceof InitializingBean) {
			InitializingBean ib = (InitializingBean) resource;
			ib.initialize();
		} else {
			String method = definition.initializingMethod();
			Reflect.on(resource).method(method).withoutArgs().invoke();
		}

		return resource;
	}

	@Override
	public void setBeanFactory(BeanFactory beanFactory) {
		// Not needed
	}

}
